package com.frame.database.proxy;

import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.frame.database.DataException;
import com.frame.hibernate.*;

public class HibernateProxy  implements MethodInterceptor{
	public HibernateProxy(){

	}

	private Session session;
	private Transaction transaction;

	public Object intercept(Object obj, Method method, Object[] pams, MethodProxy proxy) throws Throwable {
		// TODO Auto-generated method stub
		Object o=null;
		String methodName=method.getName();
		if("getSession".equals(methodName)){
			createSession();
			return session;
		}else{
			try{
				o=proxy.invokeSuper(obj,pams);
//				if(session!=null && session.isOpen())
//				transaction.commit();
			}
			catch(Exception e){
				e.printStackTrace();
				try{
//					if(session!=null && session.isOpen())
//						transaction.rollback();
				}catch(Exception re){re.printStackTrace();}
				Throwable cause = e.getCause();
				throw new DataException(e.getMessage(),cause);
			}
			finally{
				closeSession();
			}
		}
		return o;
	}

	public void createSession() throws Exception{
		session=HibernateUtil.currentSession();
//		transaction=session.beginTransaction();
	}

	public void closeSession(){
		try{
			HibernateUtil.closeSession();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
